/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package replica.communication;

import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import replica.transaction.FrontEnd;

/**
 *
 * @author Elena
 */
public class MessageDispatcherReplicaServer implements MessageDispatcher{
    
        
        private Connection connection = null;
        private Destination dest = null;
        private MessageConsumer consumer = null;
        private ObjectMessage message = null;
        private List<FrontEnd> frontends;
        
        
   public MessageDispatcherReplicaServer(List<FrontEnd> frontend) {
       this.frontends =frontend; 
        try {
            consume();
        } catch (NamingException ex) 
        {
            Logger.getLogger(MessageDispatcherReplicaServer.class.getName()).log(Level.SEVERE, null, ex);
                    System.exit(-846);
        }
    }
 
    public void consume () throws NamingException 
    {
        
 
       try {
            System.out.println(  "MessageDispatcherReplicaServer: starting");
            Properties env = new Properties( );
            InitialContext jndi = new InitialContext(env);

            ConnectionFactory conFactory =(ConnectionFactory)jndi.lookup("jms/myConnectionFactory");
            connection = conFactory.createConnection();

 
            Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
            Queue queue = (Queue)jndi.lookup("jms/myQueue");
            consumer = session.createConsumer(queue);
            connection.start();
            
            Message m=null;

            while (true) 
            {
                System.out.println("MessageDispatcherReplicaServer: listening for msg");
                m = consumer.receive();
                Messaggio castedMessage=null;
              
              
                if (m==null) 
                    throw new NullPointerException("MessageDispatcherReplicaServer: Received message "+m);
                else
                {
                        message = (ObjectMessage) m;
                        castedMessage =(Messaggio)message.getObject();
                        System.out.println("MessageDispatcherReplicaServer: received message: "+castedMessage);
                        long nodeId = castedMessage.getNodeId();
            
                        FrontEnd destination=null;
                        for(FrontEnd f: frontends)
                            if(nodeId==f.getNodeId())
                                destination=f;
                        
                        if (destination==null)
                            throw new NullPointerException("No FrontEnd was found for node"
                                    +nodeId);
                        
                        destination.onStatusReceived(castedMessage.status());
                        //destination.stopWaiting();
                        System.out.println("Sono dopo onStatusReceiver");
                 }
            }
            
        }
       /*
       catch(javax.naming.NamingException ne)
        {
            System.err.println("ERROR: Maybe your glassfish server had a previos unexpected "
                + "error. Stop glassfish, kill all java processes on your S.O., deploy all, "
                    + "and start again. See you soon");
            ne.printStackTrace();
            System.exit(-32465);
        }
        * 
        */
       catch (Exception e) {
           System.out.println("Errore dovuto allo spegnimento improvviso del FrontEnd");
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                }
            }
        }
    }
    
    
    
}
